package com.tanhua.server.service;

import com.tanhua.domain.db.QuizBook;
import com.tanhua.domain.db.QuizQuestion;
import com.tanhua.domain.db.QuizReport;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.db.QuizBookApi;
import com.tanhua.dubbo.api.db.QuizQuestionApi;
import com.tanhua.dubbo.api.db.QuizReportApi;
import com.tanhua.dubbo.api.db.QuizStarApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TestSoulService {

    @Reference
    private QuizStarApi quizStarApi;

    @Reference
    private QuizBookApi quizBookApi;

    @Reference
    private QuizReportApi quizReportApi;

    @Reference
    private QuizQuestionApi quizQuestionApi;

    @Autowired
    private RedisTemplate redisTemplate;

    //redis中存储问题的键
    private final String questionKey = "QUIZ_QUESTION_ITEM_";

    /**
     * 问卷列表
     *
     * @return
     */
    public List<QueryQuestionBook> queryBookList() {


        Long userId = UserHolder.getUserId();
        // 查询用户星级表,得到用户当前星级
        Integer userStar = quizStarApi.queryUserStar(userId);
        log.debug("**********************userStar={}*******************", userStar);

        //查询问卷表
        List<QuizBook> quizBookList = quizBookApi.queryQuizBook();
        log.debug("**********************quizBookList={}*******************", quizBookList);

        //查询所有试题的总数
        int count = quizQuestionApi.queryCount();

        //封装返回vo
        List<QueryQuestionBook> resultVo = new ArrayList<>();

        for (QuizBook quizBook : quizBookList) {

            //获得问卷id
            Integer bookId = quizBook.getBookId();

            //封装试题列表 questions
            List<QuestionItem> questions = new ArrayList<>();

            //创建一个map集合,需要得到 5个试题对象
            Map<Integer, QuizQuestion> countMap = new HashMap<>();
            while (countMap.size() <= 5) {
                //生成随机数
                int randomNum = RandomUtils.nextInt(1, (count + 1));
                String redisKey = questionKey + randomNum;
                //查询redis
                QuizQuestion quizQuestion = (QuizQuestion) redisTemplate.opsForValue().get(redisKey);

                //获得试题的bookId
//                Integer questionBookId = quizQuestion.getBookId();

                if (quizQuestion.getBookId() .equals(bookId) ) {
                    countMap.put(randomNum, quizQuestion);
                }
            }
            //将查询到的5个试题对象存入list集合中
            Collection<QuizQuestion> questionList = countMap.values();


            //------------------------试题列表
            //遍历问题列表得到问题
            for (QuizQuestion question : questionList) {
                //-----------------------选项列表
                //得到选项列表
                //A.蓝色,B.黑色,C.绿色,D.红色
                String selects = question.getSelects();
                //获得每个选项
                String[] seleclist = selects.split(",");
                //封装选项列表Vo对象
                List<OptionItem> optionItemList = new ArrayList<>();
                //遍历选项列表,得到选项编号和选项
//                for (int i = 0; i < seleclist.length; i++) {
//                    String[] split = seleclist[i].split(".");
//                    System.out.println(split);
//                }

                for (String select : seleclist) {
                    //封装选项id和选项Vo对象
                    OptionItem optionItem = new OptionItem();
                    //拆分获得选项id和选项
                    log.debug("--------------------select={}-----------------------------", select);
//                    String[] idAndOption = select.split(".");
                    select.trim();
                    String[] idAndOption = select.split("\\.");
                    log.debug("-------------------------idAndOption={}--------------------", Arrays.toString(idAndOption));
                    //添加选项编号
                    optionItem.setId(idAndOption[0]);
                    //添加选项内容
                    optionItem.setOption(idAndOption[1]);
                    //放进选项列表Vo中
                    optionItemList.add(optionItem);
                }
                //-----------------------选项列表

                //试题编号
                Integer questNum = question.getNum();
                //题目
                String content = question.getContent();

                //问题
                QuestionItem questionItem = new QuestionItem();

                questionItem.setId(questNum.toString());
                questionItem.setQuestion(content);
                questionItem.setOptions(optionItemList);
                //------------------------试题列表

                //将封装好的试题放进list中用于返回vo
                questions.add(questionItem);

            }

            //查询最新报告id
            Integer reportId = quizReportApi.queryReportId(userId, bookId);
            log.debug("**********************reportId={}*******************", reportId);

            //最终返回结果需要的数据:
            String name = quizBook.getBookName();
            String cover = quizBook.getBookCover();
            String level = quizBook.getLevel();
            String star = quizBook.getStar();

            QueryQuestionBook queryVo = new QueryQuestionBook();

            //用户星级和问卷星级比较(用户星级>=问卷星级时为0,否则为1)
            Integer isLock = 1;//锁住
            if (userStar >= Integer.parseInt(star)) {
                isLock = 0;//解锁
            }

            queryVo.setId(bookId.toString());//问卷编号
            queryVo.setName(name);//问卷名称
            queryVo.setCover(cover);//封面
            queryVo.setLevel(level);//级别
            queryVo.setStar(Integer.parseInt(star));//星级
            queryVo.setQuestions(questions);//试题
            queryVo.setIsLock(isLock);//是否锁住（0解锁，1锁住）

            if (reportId != null) {
                queryVo.setReportId(reportId.toString());//最新报告id
            } else {
                queryVo.setReportId(null);//无最新报告
            }

            resultVo.add(queryVo);
        }

        //返回问卷列表数据
        return resultVo;
    }


    /**
     * 测灵魂-提交问卷
     * @param answerItem
     * @return
     */
    public Integer querySubmitQuiz(List<AnswerItemVo> answerItem) {
        //获取用户Id
        Long userId = UserHolder.getUserId();
        //遍历接收的结果
        int score = 0;
        int bookId = 0;
        for (AnswerItemVo answerItemVo : answerItem) {
            String questionId = answerItemVo.getQuestionId();
            String optionId = answerItemVo.getOptionId();
            //根据问题编号查找问题
            QuizQuestion quizQuestion =(QuizQuestion) redisTemplate.boundValueOps(questionKey+questionId).get();
            bookId = quizQuestion.getBookId();
            if(redisTemplate.hasKey(questionKey+questionId)){
                String answer = quizQuestion.getAnswer();
                //切割标点符号的到分数,选项和对应分数
                String[] split = answer.split(",");
                //判断是否包含分数
                for (String as : split) {
                    //判断是否包含前端发送的选项数据
                    if(as.contains(optionId)){
                        String sc= as.substring(as.lastIndexOf(".")+1);
                        //累加分数
                        score += Integer.valueOf(sc);
                    }
                }
            }
        }
        return quizReportApi.queryQuizReport(score,userId,bookId);
    }

    /**
     * 根据报告id查询结果
     *
     * @param reportId
     * @return
     */
    public QueryReportVo queryReport(Integer reportId) {
        QueryReportVo queryReportVo = new QueryReportVo();
        //根据id查询报告结果
        QuizReport quizReport = quizReportApi.queryReportById(reportId);
        //封装结果
        queryReportVo.setConclusion(quizReport.getConclusion());
        queryReportVo.setCover(quizReport.getReportCover());
        List<DimensionItem> dimensions = Arrays.stream(quizReport.getDimensions().split(",")).map(s -> {
            DimensionItem dimensionItem = new DimensionItem();
            String[] split = s.split("\\:");
            dimensionItem.setKey(split[0]);
            dimensionItem.setValue(split[1]);
            return dimensionItem;
        }).collect(Collectors.toList());
        queryReportVo.setDimensions(dimensions);

        //根据分数查询临近用户id值
        Integer[] userIds = quizReportApi.queryRangeUserReport(quizReport.getUserId(), quizReport.getScore(), 5);
        //根据id查询最近用户头像与封面
        List<SimilarUser> similarUsers = quizReportApi.querySimilarUsers(userIds);
        queryReportVo.setSimilarYou(similarUsers);
        return queryReportVo;
    }
}
